<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--设备类型数据-->
      <el-col :span="spanColLeft" :xs="24">
        <div class="head-container" style="margin-bottom: 10px">
          <span><i class="el-icon-collection"></i> 设备类型树</span>
        </div>
        <div class="head-container">
          <el-input
            v-model="drtypename"
            placeholder="请输入设备类型名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deviceTypeOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--设备信息数据-->
      <el-col :span="spanColRight" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="设备名称" prop="drname">
            <el-input
              v-model="queryParams.drname"
              placeholder="请输入设备名称（中文）"
              clearable
              @keyup.enter.native="handleQuery"
              id="drname"
            />
          </el-form-item>
          <el-form-item label="英文名称" prop="drnameEN">
            <el-input
              v-model="queryParams.drnameEN"
              placeholder="请输入设备名称（英文）"
              clearable
              @keyup.enter.native="handleQuery"
              id="drnameEN"
            />
          </el-form-item>
          <el-form-item label="设备编码" prop="drcode">
            <el-input
              v-model="queryParams.drcode"
              placeholder="请输入设备编码"
              clearable
              @keyup.enter.native="handleQuery"
              id="drcode"
            />
          </el-form-item>
          <!--      <el-form-item label="负责人" prop="userid">
                  <el-input
                    v-model="queryParams.userid"
                    placeholder="请输入负责人"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>-->
          <el-form-item label="使用状态" prop="drUsestate">
            <el-select v-model="queryParams.drUsestate" placeholder="请选择使用状态" id="drUsestate" @change="handleQuery" clearable>
              <el-option
                v-for="dict in dict.type.sys_dr_use_state"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <!--      <el-form-item label="使用说明" prop="drUseexplain">
                  <el-input
                    v-model="queryParams.drUseexplain"
                    placeholder="请输入使用说明"
                    clearable
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>-->
          <el-form-item label="备注" prop="info">
            <el-input
              v-model="queryParams.info"
              placeholder="请输入备注"
              clearable
              @keyup.enter.native="handleQuery"
              id="info"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-d-arrow-left"
              size="mini"
              @click="handleShowLeft"
            >隐藏/显示左侧选择树</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:drinfo:add']"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:drinfo:edit']"
            >修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:drinfo:remove']"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              icon="el-icon-upload2"
              size="mini"
              @click="handleImport"
              v-hasPermi="['system:drinfo:import']"
            >导入</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExport"
              v-hasPermi="['system:drinfo:export']"
            >导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="drinfoList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="设备ID" align="center" prop="drid" width="60"/>
          <el-table-column label="设备名称(中文)" align="center" width="150" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <router-link :to="'/system/drInfo-reg-list/index/' + scope.row.drtypeid  + '/' + scope.row.drid + '/' + myEscape(scope.row.drname)" class="link-type">
                <span>{{ scope.row.drname }}</span>
              </router-link>
            </template>
          </el-table-column>
          <el-table-column label="英文名称" align="center" prop="drnameEN" width="210" :show-overflow-tooltip="true"/>
          <el-table-column label="设备编码" align="center" prop="drcode" width="80"/>
          <el-table-column label="设备类型" align="center" prop="drtypename" width="90" :show-overflow-tooltip="true"/>
          <!--      <el-table-column label="统一的设备编制" align="center" prop="MDcode" />-->
          <!--      <el-table-column label="类型用途" align="center" prop="typeYT" />-->
          <el-table-column label="所属建筑" align="center" prop="buildName" width="80" :show-overflow-tooltip="true"/>
          <el-table-column label="楼层" align="center" prop="floorName" width="80"/>
          <el-table-column label="区域" align="center" prop="areaName" width="80"/>
          <el-table-column label="部门" align="center" prop="departmentid" :show-overflow-tooltip="true"/>
          <!--      <el-table-column label="负责人" align="center" prop="userid" />-->
          <!--      <el-table-column label="资产类别。对应assets表" align="center" prop="assetsTypeid" />
                <el-table-column label="用于视频链接的id" align="center" prop="spid" />
                <el-table-column label="设备操作手册id" align="center" prop="instructionsid" />-->
          <!--      <el-table-column label="设备型号" align="center" prop="drManufacturestyle" />
                <el-table-column label="生产厂家" align="center" prop="drManufacturefactory" />
                <el-table-column label="厂家电话" align="center" prop="drFactoryphone" />
                <el-table-column label="安装时间" align="center" prop="drInstalltime" width="180">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.drInstalltime, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="安装厂家" align="center" prop="drInstallfactory" />
                <el-table-column label="安装电话" align="center" prop="drInstallphone" />-->
          <el-table-column label="使用状态" align="center" prop="drUsestate" width="80">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.sys_dr_use_state" :value="scope.row.drUsestate"/>
            </template>
          </el-table-column>
          <!--      <el-table-column label="使用说明" align="center" prop="drUseexplain" />-->
          <!--      <el-table-column label="设备X坐标" align="center" prop="pointX" />
                <el-table-column label="设备Y坐标" align="center" prop="pointY" />
                <el-table-column label="设备Z坐标" align="center" prop="pointZ" />
                <el-table-column label="设备图标路径" align="center" prop="iconpath" />
                <el-table-column label="坐标类型Random(随机)Seting(设置)" align="center" prop="pointType" />-->
          <el-table-column label="备注" align="center" prop="info" :show-overflow-tooltip="true"/>
          <el-table-column label="2D模型地址" align="center" prop="model2dIp" :show-overflow-tooltip="true"/>
          <el-table-column label="2D绑定变量" align="center" prop="model2dDataid" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:drinfo:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['system:drinfo:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport + '&dbName=' + upload.dbName"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的项目设备列表数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改设备信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1300px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备类型" prop="drtypeid">
              <treeselect v-model="form.drtypeid" :options="drtypeinfoOptions" :normalizer="normalizer" placeholder="请选择设备类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="设备名称" prop="drname">
              <el-input v-model="form.drname" placeholder="请输入设备名称（中文）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="设备编码" prop="drcode">
              <el-input v-model="form.drcode" placeholder="如CHP1，CT2，SY，FM302，P101，P102，RHT等等" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="英文名称" prop="drnameEN">
              <el-input v-model="form.drnameEN" placeholder="请输入设备名称（英文）" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="使用状态" prop="drUsestate">
              <el-select v-model="form.drUsestate" placeholder="请选择使用状态">
                <el-option
                  v-for="dict in dict.type.sys_dr_use_state"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="info">
              <el-input v-model="form.info" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>

<!--        <el-form-item label="统一的设备编制" prop="MDcode">
          <el-input v-model="form.MDcode" placeholder="请输入统一的设备编制" />
        </el-form-item>
        <el-form-item label="类型用途" prop="typeYT">
          <el-input v-model="form.typeYT" placeholder="请输入类型用途" />
        </el-form-item>
        <el-form-item label="负责人id，对应appuser表ID" prop="userid">
          <el-input v-model="form.userid" placeholder="请输入负责人id，对应appuser表ID" />
        </el-form-item>
        <el-form-item label="资产类别。对应assets表" prop="assetsTypeid">
          <el-input v-model="form.assetsTypeid" placeholder="请输入资产类别。对应assets表" />
        </el-form-item>
        <el-form-item label="用于视频链接的id" prop="spid">
          <el-input v-model="form.spid" placeholder="请输入用于视频链接的id" />
        </el-form-item>
        <el-form-item label="设备操作手册id" prop="instructionsid">
          <el-input v-model="form.instructionsid" placeholder="请输入设备操作手册id" />
        </el-form-item>
        <el-form-item label="设备型号" prop="drManufacturestyle">
          <el-input v-model="form.drManufacturestyle" placeholder="请输入设备型号" />
        </el-form-item>
        <el-form-item label="设备生产厂家" prop="drManufacturefactory">
          <el-input v-model="form.drManufacturefactory" placeholder="请输入设备生产厂家" />
        </el-form-item>
        <el-form-item label="生产厂家电话" prop="drFactoryphone">
          <el-input v-model="form.drFactoryphone" placeholder="请输入生产厂家电话" />
        </el-form-item>
        <el-form-item label="安装时间" prop="drInstalltime">
          <el-date-picker clearable
            v-model="form.drInstalltime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择安装时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="安装厂家" prop="drInstallfactory">
          <el-input v-model="form.drInstallfactory" placeholder="请输入安装厂家" />
        </el-form-item>
        <el-form-item label="安装厂家电话" prop="drInstallphone">
          <el-input v-model="form.drInstallphone" placeholder="请输入安装厂家电话" />
        </el-form-item>
        <el-form-item label="使用说明" prop="drUseexplain">
          <el-input v-model="form.drUseexplain" placeholder="请输入使用说明" />
        </el-form-item>
        <el-form-item label="设备X坐标" prop="pointX">
          <el-input v-model="form.pointX" placeholder="请输入设备X坐标" />
        </el-form-item>
        <el-form-item label="设备Y坐标" prop="pointY">
          <el-input v-model="form.pointY" placeholder="请输入设备Y坐标" />
        </el-form-item>
        <el-form-item label="设备Z坐标" prop="pointZ">
          <el-input v-model="form.pointZ" placeholder="请输入设备Z坐标" />
        </el-form-item>
        <el-form-item label="设备图标路径" prop="iconpath">
          <el-input v-model="form.iconpath" placeholder="请输入设备图标路径" />
        </el-form-item>-->

        <el-row>
          <el-col :span="24">
            <el-form-item label="2D地址" prop="model2dIp">
              <el-input v-model="form.model2dIp" placeholder="请输入设备的2D模型地址，有多个地址用逗号隔开，如：https://ln.szgreenenergy.com:4011/2d/device/ch1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="2D变量" prop="model2dDataid">
              <el-input v-model="form.model2dDataid" type="textarea" placeholder="请输入2D模型绑定的寄存器变量，如CH1-502-40001:10,CH1-502-40001:11,CH1-502-40001:12,CH1-502-40001:13,CH1-502-40001:9,CH1-506-40437,CH1-506-40452,CH1-506-40453等等" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">设备属性变量信息列表</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddReg">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteReg">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="regList" :row-class-name="rowRegIndex" @selection-change="handleRegSelectionChange" ref="reg">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="变量标识" prop="tagName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tagName" placeholder="请输入变量标识，如：CHP1-506-41303" />
            </template>
          </el-table-column>
          <el-table-column label="变量名称" prop="regName" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regName" placeholder="请输入变量名称，如：CHP1功率" />
            </template>
          </el-table-column>
          <el-table-column label="英文名称" prop="regNameen" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regNameen" placeholder="请输入变量英文名称，如CHP1 Power" readonly/>
            </template>
          </el-table-column>
          <el-table-column label="当前值" prop="tagValue" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tagValue" placeholder="请输入寄存器当前值" />
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="regUnits" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regUnits" placeholder="请输入单位" />
            </template>
          </el-table-column>
          <el-table-column label="数据回显" prop="regSub" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.regSub" placeholder="请选择数据回显" clearable>
                <el-option
                  v-for="item in subOptions"
                  :key="item.subid"
                  :label="item.subname"
                  :value="String(item.subid)"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="值类型" prop="regType" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.regType" placeholder="请选择设备属性值类型">
                <el-option
                  v-for="dict in dict.type.sys_value_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="读写" prop="regReadwrite" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.regReadwrite" placeholder="请选择读写类型">
                <el-option
                  v-for="dict in dict.type.sys_read_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="保存周期" prop="tagTime" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.tagTime" placeholder="请选择变量保存周期">
                <el-option
                  v-for="dict in dict.type.sys_data_save_time"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="分组" prop="regGroupId" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.regGroupId" placeholder="变量分组" clearable>
                <el-option
                  v-for="group in groupOptions"
                  :key="group.id"
                  :label="group.groupName"
                  :value="group.id"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="排序" prop="regListshowlevel" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regListshowlevel" placeholder="请输入分组内顺序" />
            </template>
          </el-table-column>
          <el-table-column label="点位类型" prop="regDrshowtype" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.regDrshowtype" placeholder="请选择设备属性的点位类型">
                <el-option
                  v-for="dict in dict.type.sys_reg_dr_show_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>

<!--          <el-table-column label="$comment" prop="regDrsub" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regDrsub" placeholder="请输入$comment" />
            </template>
          </el-table-column>
          <el-table-column label="公式" prop="regmath" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regmath" placeholder="请输入公式" />
            </template>
          </el-table-column>
          <el-table-column label="颜色" prop="regcolor" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.regcolor" placeholder="请输入颜色" />
            </template>
          </el-table-column>-->
          <el-table-column label="3D展示" prop="isThreedShow" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isThreedShow" placeholder="请选择是否3D展示">
                <el-option
                  v-for="dict in dict.type.sys_is_show"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否历史" prop="isHistory" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isHistory" placeholder="请选择是否是历史记录">
                <el-option
                  v-for="dict in dict.type.sys_is_custom_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否能耗" prop="isEnergy" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isEnergy" placeholder="请选择是否是能耗记录">
                <el-option
                  v-for="dict in dict.type.sys_is_energy"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>
<!--          <el-table-column label="是否报警" prop="isAlarm" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isAlarm" placeholder="请选择是否报警">
                <el-option
                  v-for="dict in dict.type.sys_is_alarm"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>-->
<!--          <el-table-column label="报警类型" prop="alarmtype" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.alarmtype" placeholder="请选择报警类型">
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </template>
          </el-table-column>-->
<!--          <el-table-column label="报警级别(仅布尔变量)" prop="alarmLevel" width="150">
            <template slot-scope="scope">
              <el-select v-model="scope.row.alarmLevel" placeholder="报警等级(仅布尔变量)" clearable>
                <el-option
                  v-for="alarmLevel in alarmLevelOptions"
                  :key="alarmLevel.alarmtypelevel"
                  :label="alarmLevel.alarmtypeExpain"
                  :value="alarmLevel.alarmtypelevel"
                ></el-option>
              </el-select>
            </template>
          </el-table-column>-->
<!--          <el-table-column label="最小值" prop="valueMin" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.valueMin" placeholder="请输入最小值" />
            </template>
          </el-table-column>
          <el-table-column label="最大值" prop="valueMax" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.valueMax" placeholder="请输入最大值" />
            </template>
          </el-table-column>
          <el-table-column label="与或条件" prop="andOr" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.andOr" placeholder="请输入与或条件" />
            </template>
          </el-table-column>-->
<!--          <el-table-column label="报警状态" prop="tagAlarmState" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tagAlarmState" placeholder="请输入报警状态" />
            </template>
          </el-table-column>-->
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDrinfo, getDrinfo, delDrinfo, addDrinfo, updateDrinfo,deviceTypeTreeSelect,drTypeSelect,groupSelect,alarmLevelSelect,getSubOptionSelect,getDbName } from "@/api/system/drinfo";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {getToken} from "@/utils/auth";

export default {
  name: "Drinfo",
  components: {
    Treeselect
  },
  dicts: ['sys_dr_use_state', 'sys_reg_dr_show_type', 'sys_is_custom_type', 'sys_is_show', 'sys_is_energy', 'sys_read_type', 'sys_data_save_time', 'sys_is_alarm', 'sys_value_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedReg: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showLeft: true,
      spanColLeft: 3,
      spanColRight: 21,
      // 总条数
      total: 0,
      // 设备信息管理表格数据
      drinfoList: [],
      // 属性变量管理表格数据
      regList: [],
      // 设备类型管理树选项
      drtypeinfoOptions: [],
      // 设备类型选项
      deviceTypeOptions: undefined,
      //变量分组
      groupOptions: undefined,
      //报警等级
      alarmLevelOptions: undefined,
      // 设备属性回显定义列表
      subOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 设备类型名称
      drtypename: undefined,
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        dbName : getDbName(),
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/drinfo/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drname: null,
        drnameEN: null,
        drcode: null,
        drtypeid: null,
        buildid: null,
        floorId: null,
        areaId: null,
        departmentid: null,
        userid: null,
        drUsestate: null,
        drUseexplain: null,
        info: null,
      },
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    drtypename(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getList();
    this.getDrTypeSelect();
    this.getDeviceTypeTree();
    this.getSubList();
  },
  methods: {
    /** 查询设备信息管理列表 */
    getList() {
      this.loading = true;
      listDrinfo(this.queryParams).then(response => {
        this.drinfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleShowLeft(){
      const show = this.showLeft;
      if(show){
        this.showLeft = false;
        this.spanColLeft = 0;
        this.spanColRight = 24;
      }else{
        this.showLeft = true;
        this.spanColLeft = 3;
        this.spanColRight = 21;
      }
    },
    /** 查询字典类型列表 */
    getSubList() {
      getSubOptionSelect().then(response => {
        this.subOptions = response.data;
      });
    },
    /** 转换设备类型管理数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.drtypeid,
        label: node.drtypename,
        children: node.children
      };
    },
    /** 查询设备类型下拉树结构，下拉列表框展示 */
    getDrTypeSelect() {
      drTypeSelect().then(response => {
        this.drtypeinfoOptions = [];
        const data = { drtypeid: 0, drtypename: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "drtypeid", "parentId");
        this.drtypeinfoOptions.push(data);
      });
    },
    /** 查询设备类型下拉树结构，左侧展示 */
    getDeviceTypeTree() {
      deviceTypeTreeSelect().then(response => {
        this.deviceTypeOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.drtypeid = data.id;
      this.handleQuery();
    },
    /** 查询变量分组 */
    getGroupSelect() {
      groupSelect().then(response => {
        this.groupOptions = response.data;
      });
    },
    /** 查询报警等级类型 */
    getAlarmLevelSelect() {
      alarmLevelSelect().then(response => {
        this.alarmLevelOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        drid: null,
        drname: null,
        drnameEN: null,
        drcode: null,
        drtypeid: null,
        MDcode: null,
        typeYT: null,
        buildid: null,
        floorId: null,
        areaId: null,
        departmentid: null,
        userid: null,
        assetsTypeid: null,
        spid: null,
        instructionsid: null,
        drManufacturestyle: null,
        drManufacturefactory: null,
        drFactoryphone: null,
        drInstalltime: null,
        drInstallfactory: null,
        drInstallphone: null,
        drUsestate: null,
        drUseexplain: null,
        pointX: null,
        pointY: null,
        pointZ: null,
        iconpath: null,
        pointType: null,
        info: null,
        model2dIp: null,
        model2dDataid: null
      };
      this.regList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.drtypeid = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.drid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    myEscape(drName){
      let newDrName = null;
      if(drName != null && drName.includes('#')){
        newDrName = drName.replaceAll('#','|');
      }else{
        newDrName = drName;
      }
      return newDrName;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.getGroupSelect();
      this.getAlarmLevelSelect();
      this.reset();
      this.form.drtypeid = 0;
      this.open = true;
      this.title = "添加设备信息管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.getGroupSelect();
      this.getAlarmLevelSelect();
      this.reset();
      const drid = row.drid || this.ids
      getDrinfo(drid).then(response => {
        this.form = response.data;
        this.regList = response.data.regList;
        this.open = true;
        this.title = "修改设备信息管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.regList = this.regList;
          if (this.form.drid != null) {
            updateDrinfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDrinfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const drids = row.drid || this.ids;
      this.$modal.confirm('是否确认删除设备信息管理编号为"' + drids + '"的数据项？').then(function() {
        return delDrinfo(drids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
	/** 属性变量管理序号 */
    rowRegIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 属性变量管理添加按钮操作 */
    handleAddReg() {
      let obj = {};
      obj.tagName = "";
      obj.tagValue = "";
      obj.tagTime = "";
      obj.regName = "";
      obj.regNameen = "";
      obj.regType = "";
      obj.regUnits = "";
      obj.regReadwrite = "";
      obj.regGroupId = "";
      obj.regListshowlevel = "";
      obj.regDrshowtype = "";
      obj.regSub = "";
      obj.regDrsub = "";
      obj.regmath = "";
      obj.regcolor = "";
      obj.isThreedShow = "";
      obj.isHistory = "";
      obj.isEnergy = "";
      obj.isAlarm = "";
      obj.alarmtype = "";
      obj.alarmLevel = "";
      obj.valueMin = "";
      obj.valueMax = "";
      obj.andOr = "";
      obj.tagAlarmState = "";
      this.regList.push(obj);
    },
    /** 属性变量管理删除按钮操作 */
    handleDeleteReg() {
      if (this.checkedReg.length == 0) {
        this.$modal.msgError("请先选择要删除的属性变量管理数据");
      } else {
        const regList = this.regList;
        const checkedReg = this.checkedReg;
        this.regList = regList.filter(function(item) {
          return checkedReg.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleRegSelectionChange(selection) {
      this.checkedReg = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/drinfo/export', {
        ...this.queryParams
      }, `项目设备列表_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "项目设备列表数据导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/drinfo/importTemplate', {
      }, `drinfo_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;width:600px;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true,customClass: 'el-message-box' });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
<style type="text/css">
.el-message-box {
  width: 600px; /* 设置弹框宽度为视口宽度的一半 */
}
</style>
